<template>
  <n-card class="special-operation-card" :bordered="true" size="small">
    <template #header>
      <div class="section-header">
        <n-space align="center" :size="8">
          <n-icon :size="20" color="#e6a23c">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
              <path fill="currentColor" d="M12 2L3 5v6c0 5.55 3.84 10.74 9 12c5.16-1.26 9-6.45 9-12V5l-9-4z"/>
            </svg>
          </n-icon>
          <n-text strong>特勤处推荐</n-text>
        </n-space>
        <n-tag size="small" type="warning">高利润</n-tag>
      </div>
    </template>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <loading-skeleton type="card" :count="4" />
    </div>

    <!-- 实际内容 -->
    <div v-else-if="specialOperations.length > 0" class="special-operations-grid">
      <n-card
        v-for="operation in specialOperations"
        :key="operation.location"
        size="small"
        :bordered="false"
        class="operation-naive-card compact-card"
        @click="goToSpecialOperation(operation.location)"
      >
        <div class="operation-card-content">

          <!-- 物品信息 -->
          <div v-if="operation.item && operation.item.name" class="item-info">
            <!-- 左侧：物品图片 -->
            <div :class="['item-image-container', `grade-bg-${operation.item.grade || 1}`]">
              <n-image
                :src="operation.item.image || '/images/default-item.png'"
                class="item-image"
                :fallback-src="'/images/default-item.png'"
                :preview-disabled="true"
              />
              <div :class="['item-grade', `grade-${operation.item.grade || 1}`]">
                {{ operation.item.grade || 1 }}
              </div>
            </div>

            <!-- 右侧：物品详情 -->
            <div class="item-details">
              <!-- 物品名称和净利润 -->
              <div class="item-header">
                <div class="item-name" :title="operation.item.name">{{ operation.item.name }}</div>
                <div class="profit-info">
                  <div class="profit-label">净利润:</div>
                  <div class="profit-value">{{ (operation.item.lirun || 0).toLocaleString() }}</div>
                </div>
                <div class="location-tag">{{ operation.location }}</div>
              </div>

              <!-- 统计信息网格 -->
              <div class="stats-grid">
                <div class="stat-item">
                  <span class="stat-label">售价:</span>
                  <span class="stat-value">{{ (operation.item.sale_price || 0).toLocaleString() }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">成本:</span>
                  <span class="stat-value">{{ (operation.item.cost_price || 0).toLocaleString() }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">周期:</span>
                  <span class="stat-value">{{ operation.item.period || 0 }}小时</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">数量:</span>
                  <span class="stat-value">{{ operation.item.per_count || 0 }}个</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 无数据状态 -->
          <div v-else class="no-item">
            <div class="no-item-content">
              <n-icon size="24" color="#d0d0d0">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                  <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10s10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5l1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>
              </n-icon>
              <n-text :depth="3" style="font-size: 12px; margin-top: 4px;">{{ operation.location }}暂无数据</n-text>
            </div>
          </div>
        </div>
      </n-card>
    </div>

    <!-- 空状态 -->
    <n-empty v-else description="暂无特勤处数据" size="small" />
  </n-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getSpecialOperationList } from '@/api/specialOperation'
import type { SpecialOperationItem } from '@/types/specialOperation'
import LoadingSkeleton from '@/components/common/LoadingSkeleton.vue'
// 移除不再使用的图标导入

// 定义特勤处位置数据结构
interface SpecialOperationLocation {
  location: string
  item: SpecialOperationItem | null
}

const router = useRouter()
const loading = ref(false)
const specialOperations = ref<SpecialOperationLocation[]>([])

// 位置列表
const locations = ['工作台', '技术中心', '制药台', '防具']

// 移除不再使用的图标相关方法

// 获取特勤处数据
const fetchSpecialOperations = async () => {
  try {
    loading.value = true
    const operations: SpecialOperationLocation[] = []

    // 为每个位置获取利润最高的物品
    for (const location of locations) {
      try {
        console.log(`正在获取${location}的数据...`)
        const response = await getSpecialOperationList({
          page: 1,
          page_size: 1, // 只获取第一个（利润最高的）
          location: location,
          sort_by: 'lirun', // 按净利润排序
          sort_order: 'desc'
        })

        console.log(`${location}响应数据:`, response)

        let item = null
        if (response.code === 1 && response.data?.list?.length > 0) {
          const rawItem = response.data.list[0]
          console.log(`${location}原始物品数据:`, rawItem)

          // 数据验证和格式化
          if (rawItem && rawItem.name) {
            // 安全的图片字段处理
            const imageField = rawItem.image ||
                              (rawItem as any).image_url ||
                              (rawItem as any).pic ||
                              '/images/default-item.png'

            item = {
              ...rawItem,
              // 统一图片字段处理
              image: imageField,
              // 确保数值字段存在
              lirun: rawItem.lirun || rawItem.net_profit || 0,
              sale_price: rawItem.sale_price || rawItem.current_price || 0,
              cost_price: rawItem.cost_price || rawItem.cost || 0,
              period: rawItem.period || rawItem.production_cycle || 0,
              per_count: rawItem.per_count || rawItem.production_quantity || 0,
              grade: rawItem.grade || 1
            }
            console.log(`${location}处理后的物品数据:`, item)
          } else {
            console.warn(`${location}数据无效:`, rawItem)
          }
        } else {
          console.warn(`${location}无数据或响应异常:`, response)
        }

        operations.push({
          location,
          item
        })
      } catch (error) {
        console.error(`获取${location}数据失败:`, error)
        operations.push({
          location,
          item: null
        })
      }
    }

    console.log('最终特勤处数据:', operations)
    specialOperations.value = operations
  } catch (error) {
    console.error('获取特勤处数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 跳转到特勤处排行榜
const goToSpecialOperation = (location?: string) => {
  const query: Record<string, string> = { type: 'special-operation-ranking' }
  if (location) {
    query.location = location
  }
  router.push({
    path: '/ranking',
    query
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSpecialOperations()
})
</script>

<style scoped>
.special-operation-card {
  height: 100%;
  min-height: auto;
  display: flex;
  flex-direction: column;
}

.special-operation-card .n-card__content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 120px;
}

.special-operations-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 4px;
  margin-top: 4px;
  width: 100%;
}

.operation-naive-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  background-color: var(--n-card-color);
  position: relative;
  overflow: hidden;
  min-height: 120px;
}

.operation-naive-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-color: var(--n-primary-color);
}

/* 移动端禁用悬停效果 */
@media (hover: none) and (pointer: coarse) {
  .operation-naive-card:hover {
    transform: none;
    box-shadow: none;
  }

  .operation-naive-card:active {
    transform: scale(0.98);
    transition: transform 0.1s ease;
  }
}

.operation-card-content {
  padding: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.item-info {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  flex: 1;
}

.item-image-container {
  position: relative;
  flex-shrink: 0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 76px; /* 60px + 8px padding * 2 */
  height: 76px; /* 60px + 8px padding * 2 */
  overflow: hidden;
  transition: all 0.3s ease;
}

.item-image {
  border-radius: 4px;
  height: 60px;
  object-fit: contain;
  display: inline-flex;
}


.item-grade {
  position: absolute;
  top: -2px;
  right: -2px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: bold;
  color: white;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
}

/* 等级背景色 - 使用项目统一的颜色系统 */
.grade-bg-1 { background: var(--grade-bg-1, #cdd5d5); }
.grade-bg-2 { background: var(--grade-bg-2, #188D14); }
.grade-bg-3 { background: var(--grade-bg-3, #658BCE); }
.grade-bg-4 { background: var(--grade-bg-4, #9b61c8); }
.grade-bg-5 { background: var(--grade-bg-5, #e8a64e); }
.grade-bg-6 { background: var(--grade-bg-6, #cb464a); }

/* 等级标签颜色 */
.grade-1 { background: var(--grade-tag-1, #cdd5d5); }
.grade-2 { background: var(--grade-tag-2, #188D14); }
.grade-3 { background: var(--grade-tag-3, #658BCE); }
.grade-4 { background: var(--grade-tag-4, #9b61c8); }
.grade-5 { background: var(--grade-tag-5, #e8a64e); }
.grade-6 { background: var(--grade-tag-6, #cb464a); }

.item-details {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.item-header {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.item-name {
  font-size: 14px;
  font-weight: 600;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.profit-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.profit-label {
  font-size: 14px;
}

.profit-value {
  font-size: 14px;
  font-weight: 700;
  color: #fa4d4d;
}

.location-tag {
  align-self: flex-end;
  background: #007bff;
  color: white;
  font-size: 10px;
  font-weight: 500;
  padding: 2px 6px;
  border-radius: 4px;
  margin-top: -20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  font-weight: 400;
}

.stat-value {
  font-size: 14px;
  font-weight: 500;
}

.no-item {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  min-height: 60px;
}

.no-item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  opacity: 0.6;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .special-operations-grid {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(4, 1fr);
    gap: 8px;
    margin-top: 8px;
  }

  .operation-card-content {
    padding: 8px;
  }

  .item-info {
    gap: 8px;
    align-items: flex-start;
  }

  .item-image-container {
    padding: 6px;
    border-radius: 6px;
    width: 52px; /* 40px + 6px padding * 2 */
    height: 52px; /* 40px + 6px padding * 2 */
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    transition: all 0.3s ease;
  }


  .item-details {
    gap: 4px;
    flex: 1;
  }

  .item-header {
    gap: 3px;
  }

  .item-name {
    font-size: 13px;
    line-height: 1.2;
  }

  .profit-info {
    gap: 4px;
  }

  .profit-value {
    font-size: 13px;
  }

  .profit-label {
    font-size: 11px;
  }

  .location-tag {
    font-size: 10px;
    padding: 2px 4px;
    margin-top: -18px;
    border-radius: 3px;
  }

  .stats-grid {
    gap: 3px 6px;
  }

  .stat-label {
    font-size: 11px;
  }

  .stat-value {
    font-size: 11px;
    font-weight: 600;
  }

  .operation-naive-card {
    min-height: 90px;
    border-radius: 6px;
  }

  .item-grade {
    width: 12px;
    height: 12px;
    font-size: 8px;
    top: -2px;
    right: -2px;
  }

  .no-item {
    min-height: 60px;
  }
}

/* 超小屏幕适配 (小于480px) */
@media (max-width: 480px) {
  .special-operations-grid {
    gap: 6px;
  }

  .operation-card-content {
    padding: 6px;
  }

  .item-info {
    gap: 6px;
  }

  .item-image-container {
    padding: 4px;
    width: 44px; /* 36px + 4px padding * 2 */
    height: 44px; /* 36px + 4px padding * 2 */
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    transition: all 0.3s ease;
  }
  .location-tag {
    padding: 1px 3px;
  }

  .operation-naive-card {
    min-height: 85px;
  }

  .item-grade {
    width: 10px;
    height: 10px;
  }
}
</style>
